#!/bin/env python3
# -*- coding: utf-8 -*- (for python2.x)

import sys
import logging

log_file_default = sys.path[0] + '/all.log'

def logger_init(output_file = None):
    logging.addLevelName(50, '\033[1;91m#\033[0m')   # CRITICAL
    logging.addLevelName(40, '\033[1;91mx\033[0m')   # ERROR
    logging.addLevelName(30, '\033[1;93m!\033[0m')   # WARNING
    logging.addLevelName(20, '\033[1;97m.\033[0m')   # INFO
    logging.addLevelName(10, '\033[1;90m>\033[0m')   # DEBUG
    logging.addLevelName(0,  ' ')   # NOTSET

    log = logging.getLogger('root')
    log.setLevel(level = logging.DEBUG)

    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    console.setFormatter(logging.Formatter(fmt =
        '\033[90m%(asctime)s.%(msecs)03d\033[0m '
        '\033[32m%(filename)16s\033[90m:\033[36m%(lineno)04d\033[0m '
        '%(levelname)s %(message)s',
        datefmt = '%H:%M:%S'))
    log.addHandler(console)

    if output_file is not None:
        handler = logging.FileHandler(output_file)
        handler.setLevel(logging.INFO)
        handler.setFormatter(logging.Formatter(fmt = ('%(asctime)s '
            '%(filename)16s:%(lineno)04d %(levelname)s %(message)s')))
        log.addHandler(handler)

    return log

def menu(l, p=-1):
    while 1:
        i = 1
        print('\n ####')
        for item in l:
            print(' # %3d %s' % (i, item['name']))
            i += 1
        print(' #   0 return')

        if p == -1:
            try:
                n = int(input('input item number:'))
            except Exception as e:
                print('get number failed: %s' % e)
                continue
        else:
            n = p

        #  print('get item number:%d' % n)
        if n == 0:
            print('quit\n')
            break
        elif n < i and n > 0:
            n -= 1
            #  print('enter function: %r' % l[n]['func'])
            print(' ####')
            if l[n].get('func'):
                l[n]['func'](l[n]['param'])
            if p != -1:
                break
        else:
            print('number(%d) out of range(0~%d)' % (n, i))
            p = -1;
        n = -1;

